package io.renren.modules.sp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.constant.Constant;
import io.renren.common.utils.Result;
import io.renren.common.utils.image.DrawImageUtil;
import io.renren.common.utils.image.ImageType;
import io.renren.common.utils.image.JpegReader;
import io.renren.modules.sp.dao.*;
import io.renren.modules.sp.dto.SpTeamDTO;
import io.renren.modules.sp.dto.SpTeamUserDTO;
import io.renren.modules.sp.dto.SpUserDTO;
import io.renren.modules.sp.entity.*;
import io.renren.modules.sp.service.SpTeamUserService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sp.service.TAreaService;
import io.renren.modules.sys.dto.ParamDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;

/**
 * 领队成员
 *
 * @author whc 15953295779@126.com
 * @since 3.0 2023-04-20
 */
@Service
public class SpTeamUserServiceImpl extends CrudServiceImpl<SpTeamUserDao, SpTeamUserEntity, SpTeamUserDTO> implements SpTeamUserService {

    @Autowired
    private SpTeamUserDao spTeamUserDao;
    @Autowired
    private SpTeamDao spTeamDao;
    @Autowired
    private TAreaService tAreaService;
    @Autowired
    private SpUserDao spUserDao;
    @Autowired
    private SpMatchItemTeamUserDao spMatchItemTeamUserDao;
    @Autowired
    private SpMatchItemTeamDao spMatchItemTeamDao;


    @Override
    public QueryWrapper<SpTeamUserEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<SpTeamUserEntity> wrapper = new QueryWrapper<>();
        String teamId = (String)params.get("teamId");
        wrapper.eq(StringUtils.isNotBlank(teamId), "team_id", teamId);
        wrapper.orderByAsc("type");
        wrapper.orderByAsc("id");
        return wrapper;
    }

    //保存代表队成员
    @Override
    public Result saveTeamUser(SpTeamUserDTO dto){
        /**
         * 代表队的成员：
         * 1、保存副领队
         * 2、保存选手
         */
        if(dto.getType() == Constant.TeamUserType.LEADER_FU.getValue() ) {
            //1、保存副领队
            QueryWrapper<SpTeamUserEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("team_id", dto.getTeamId());
            wrapper.eq("type", Constant.TeamUserType.LEADER_FU.getValue());
            List<SpTeamUserEntity> list = spTeamUserDao.selectList(wrapper);
            // 副领队不能超过3人
            if(list != null && list.size() > 3){
                //throw new RuntimeException("代表队领队不可超过4人");
                return new Result().error("代表队领队不可超过4人");
            }
        }
        // 保存副领队/选手
        SpTeamUserEntity spTeamUserEntity = new SpTeamUserEntity();
        BeanUtils.copyProperties(dto, spTeamUserEntity);
        spTeamUserDao.insert(spTeamUserEntity);
        return new Result().ok("保存成功");
    }

    //按照条件查询
    @Override
    public List<SpTeamUserEntity> queryList(QueryWrapper<SpTeamUserEntity> params){
        List<SpTeamUserEntity> list = baseDao.selectList(params);
        return list;
    }

    //查询代表队信息
    @Override
    public Result<Map<String,Object>> queryTeamUserList(SpUserDTO user) {
        Long teamId = null;
        //查询代表队
        List<SpTeamEntity> list = spTeamDao.selectList(
                new QueryWrapper<SpTeamEntity>()
                        .eq("creator", user.getId())
        );
        List<SpTeamUserEntity> teamuserList = spTeamUserDao.selectList(
                new QueryWrapper<SpTeamUserEntity>()
                        .eq("user_id", user.getId())
                        .eq("type", Constant.TeamUserType.LEADER.getValue())
        );

        if(list!=null && list.size()>0){
            teamId = list.get(0).getId();
        }

        if(teamuserList!=null && teamuserList.size()>0){
            teamId = teamuserList.get(0).getTeamId();
        }

        if (teamId==null) {
            return new Result<Map<String, Object>>().error("请先创建代表队");
        } else {
            SpTeamEntity data = spTeamDao.selectById(teamId);
            if(data!=null) {
                String province = data.getProvince();
                String city = data.getCity();
                //List<ParamDto> areaList = tAreaService.queryByCode(province);
                TAreaEntity areaEntity = tAreaService.getByCode(province);
                data.setProvince(areaEntity.getCode());
                data.setProvinceName(areaEntity.getName());
                data.setJiancheng(areaEntity.getJiancheng());
                List<ParamDto> cityList = tAreaService.queryByCode(city);
                data.setCity(cityList.size()>0?cityList.get(0).getCode():"");
                data.setCityName(cityList.size()>0?cityList.get(0).getName():"");
                //创建人
                SpUserEntity creator = spUserDao.selectById(data.getCreator());
                //查询主领队
                List<Map<String, Object>> leaderList = spUserDao.queryList(data.getId(), Constant.TeamUserType.LEADER.getValue());
                //查询副领队
                List<Map<String, Object>> fuLeaderList = spUserDao.queryList(data.getId(), Constant.TeamUserType.LEADER_FU.getValue());
                Map result = new HashMap();
                result.put("team", data);
                result.put("creator", creator);
                result.put("leader", leaderList.size() > 0 ? leaderList.get(0) : null);
                result.put("fuLeaderList", fuLeaderList);
                return new Result<Map<String, Object>>().ok(result);
            }else{
                return new Result<Map<String, Object>>().error("数据异常，未查询到领队信息");
            }
        }
    }

    /**
     * 删除代表队成员
     * 改为完赛状态下可以解绑
     */
    @Override
    public Result<Map<String,Object>> delTeamUser(Long userId, Long teamUserId){
        //查询是否有报名赛项记录
        List<SpMatchItemTeamUserEntity> list = spMatchItemTeamUserDao.selectList(
                new QueryWrapper<SpMatchItemTeamUserEntity>()
                        .eq("user_id",userId)
        );

        if(list!=null && list.size()>0){
            //return new Result<Map<String, Object>>().error("该成员已报名赛项，不能删除");
            // 判断是否全部完赛
            boolean flag = true;
            for (SpMatchItemTeamUserEntity entity : list) {
                SpMatchItemTeamEntity teamEntity = spMatchItemTeamDao.selectById(entity.getMatchItemTeamId());
                // 2完赛、2的特殊状态-已确认晋级、5特殊状态-放弃晋级、 6晋级成功、7弃权、8驳回 10状态时报名已截 可以解绑
                if(teamEntity!=null) {
                    System.out.println("teamEntity.getStatus():"+teamEntity.getStatus() + " teamEntity.getRejectReason():"+teamEntity.getRejectReason());
                    boolean bflag =  !(
                            teamEntity.getStatus() == 2
                                    || (teamEntity.getStatus() == 5  && teamEntity.getRejectReason() != "放弃晋级")
                                    || teamEntity.getStatus() == 7
                                    || teamEntity.getStatus() == 8
                                    || teamEntity.getStatus() == 6
                                    || teamEntity.getStatus() == 10
                    );
                    System.out.println(bflag);

                    if (
                            !(
                            teamEntity.getStatus() == 2
                            || (teamEntity.getStatus() == 5  && teamEntity.getRejectReason() != "放弃晋级")
                            || teamEntity.getStatus() == 7
                            || teamEntity.getStatus() == 8
                            || teamEntity.getStatus() == 6
                            || teamEntity.getStatus() == 10
                            )
                    ) {
                        flag = false;
                        break;
                    }
                }
            }
            if(flag) {
                //删除成员
                spTeamUserDao.deleteById(teamUserId);
                return new Result<Map<String, Object>>();
            }else{
                return new Result<Map<String, Object>>().error("该成员已报名赛项，不能删除");
            }
        }else{
            //删除成员
            spTeamUserDao.deleteById(teamUserId);
            return new Result<Map<String, Object>>();
        }
    }

    /**
     * 设置成主领队
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result setLeader(Long teamId, Long teamUserId) {
        //找到原来的主领队，改为副领队
        List<SpTeamUserEntity> userList = spTeamUserDao.selectList(
                new QueryWrapper<SpTeamUserEntity>()
                        .eq("team_id",teamId)
                        .eq("type",Constant.TeamUserType.LEADER.getValue())
        );
        for (SpTeamUserEntity user : userList) {
            user.setType(Constant.TeamUserType.LEADER_FU.getValue());
            spTeamUserDao.updateById(user);
        }

        SpTeamUserEntity spTeamUserEntity = new SpTeamUserEntity();
        spTeamUserEntity.setId(teamUserId);
        spTeamUserEntity.setType(Constant.TeamUserType.LEADER.getValue());
        spTeamUserDao.updateById(spTeamUserEntity);

        return new Result();
    }

    /**
     * 荣誉
     */
    public void drawRongyu() throws Exception{
        // 获取系统字体
        //getFonts();
        // 组装数据
        AllContentEntity all = mock();
        // 遍历数据并画图片
        BufferedImage image = JpegReader.readImage(JpegReader.getImgInputByUrl(all.getSourcePath()));
        for (ContentEntity item : all.getContentList()) {
            DrawImageUtil.drawContentEntity(image, item);
        }
        DrawImageUtil.saveLossLessImage(image, all.getTargetPath(), ImageType.IMAGE_TYPE_JPG);
    }





    /**
     * 奖证参数
     * @return void
     * @Author 峰影
     */
    public static AllContentEntity mock() {
        List<ContentEntity> list = new ArrayList<ContentEntity>();

        ContentEntity content0 = new ContentEntity("（山东省潍坊地区选拔赛）", "黑体",
                1, 18 * 4, 477f / 1283, 245f / 907);
        content0.setFontColor(new Color(255, 252, 252));
        list.add(content0);

        ContentEntity content1 = new ContentEntity("2023年 5月", "黑体",
                1, 12 * 4, 593f / 1283, 283f / 907);
        content1.setFontColor(new Color(255, 252, 252));
        content1.setFontSpace(10 * 3);
        list.add(content1);

        ContentEntity content2 = new ContentEntity("同学获第七届全国青少年无人机大赛（山东省", "黑体",
                0, 18 * 4, 422f / 1283, 533f / 907);
        list.add(content2);

        ContentEntity content3 = new ContentEntity("潍坊地区选拔赛）旋翼类个人空中射击赛小学组", "黑体",
                0, 18 * 4, 263f / 1283, 580f / 907);
        list.add(content3);

        ContentEntity content4 = new ContentEntity("一等奖", "隶书",
                1, 58 * 4, 483f / 1283, 660f / 907);
        content4.setFontColor(new Color(255, 2, 2));
        content4.setFontSpace(58 * 6);
        list.add(content4);

        ContentEntity content5 = new ContentEntity("潍坊市第一小学", "宋体",
                0, 10 * 4, 247f / 1283, 783f / 907);
        list.add(content5);

        ContentEntity content51 = new ContentEntity("李四", "宋体",
                0, 10 * 4, 247f / 1283, 801f / 907);
        list.add(content51);

        ContentEntity content6 = new ContentEntity("EDER7202305080001", "微软雅黑",
                1, 10 * 4, 208f / 1283, 827f / 907);
        content6.setFontSpace(9 * 3);
        list.add(content6);

        ContentEntity content7 = new ContentEntity("2023年 5月", "黑体",
                1, 11 * 4, 1008f / 1283, 842f / 907);
        content7.setFontSpace(10 * 3);
        list.add(content7);


        /*ContentEntity content8 = new ContentEntity(true, 100f / 1283, 777f / 907);
        content8.setContent("D:\\data\\f.jpg");
        list.add(content8);*/

        ContentEntity content = new ContentEntity();
        content.setContent("张 三");
        content.setFontStyle(1);
        list.add(content);


        AllContentEntity all = new AllContentEntity();
        all.setContentList(list);

        return all;
    }


}
